const app = getApp()
const adapters = require("../../utils/adapters");
import eventBus from '../../utils/eventBus';
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    header: {
      title: '锂电首页',
      whiteBg: false,
      mode: 'title',
      navBarHeight: app.globalData.navBarHeight,
      tabbarHeight: app.globalData.tabbarHeight,
      screenHeight: app.globalData.screenHeight,
      screenWidth: app.globalData.screenWidth,
    },
    device: {
      deviceId: '',
      name: '暂未连接',
      parameter: {},
    },
  },

  onPageScroll(e) {
    this.setData({
      'header.whiteBg': e.scrollTop < 130 ? false : true
    })
  },

  onLoad(options) {
    console.log('启动监听...');
    eventBus.on('device', (data) => {
      this.setData({
        device: data
      });
      console.log('收到子页面的数据:', data);
    });
  },

  async onShow(option) {
    let executeCount = 0;
    const maxTimes = 5;
    const intervalTime = 3000;
  
    // ✅ 将 setInterval 的回调改为 async 函数
    const timer = setInterval(async () => { // ⬅️ 加上 async
      executeCount++;
  
      try {
        // ✅ 现在可以使用 await 了
        const getBatteryInfoRes = await adapters.getBatteryInfo(this.data.device);
  
        if (getBatteryInfoRes.success) {
          this.setData({
            device: getBatteryInfoRes.data
          });
        }
  
        this.progressBarRefresh();
  
        console.log(`执行第 ${executeCount} 次`);
  
        // 停止条件
        if (executeCount >= maxTimes || this.data.device.power !== '') {
          clearInterval(timer);
          console.log('已完成更新');
        }
  
      } catch (error) {
        console.error('获取电池信息失败', error);
        clearInterval(timer); // 可选：出错时也停止
      }
    }, intervalTime);
  },

  onUnload() {
    console.log('关闭监听...')
    eventBus.off('device', (data) => {
      this.setData({
        device: data
      });
    })
  },

  navigatePage(e) {
    let pageName = e.currentTarget.dataset.pagename;
    wx.navigateTo({
      url: '/pages/' + pageName + '/' + pageName,
    });
  },

  async getBatteryInfo() {
    await adapters.wx.getBatteryInfo(device.deviceId, device.name)
  },
})